import React from "react";
import { Card, Button, Space, Tag, Typography, Alert } from "antd";
import { useRequest } from "ahooks";
import { history, useSearchParams } from "umi";

const { Text, Paragraph } = Typography;

// 模拟 API 请求
const fetchData = (
  id: number
): Promise<{
  id: number;
  content: string;
  timestamp: number;
  version: number;
}> => {
  return new Promise((resolve) => {
    setTimeout(() => {
      resolve({
        id,
        content: `数据内容 ${id} - 版本 ${Date.now()}`,
        timestamp: Date.now(),
        version: Math.floor(Math.random() * 1000),
      });
    }, 800);
  });
};

const RefreshPage: React.FC = () => {
  const [searchParams, setSearchParams] = useSearchParams();
  const currentId = Number(searchParams.get("id")) || 1;

  // 当 id 变化时，useRequest 会自动重新请求
  const { data, loading, error, refresh } = useRequest(
    () => fetchData(currentId),
    {
      refreshDeps: [currentId], // 当 currentId 变化时自动重新请求
      cacheKey: `data-${currentId}`,
    }
  );

  const handleIdChange = (newId: number) => {
    setSearchParams({ id: newId.toString() });
  };

  const handleRefresh = () => {
    refresh(); // 强制刷新当前数据
  };

  return (
    <div style={{ padding: "24px" }}>
      <Button
        onClick={() => history.push("/")}
        style={{ marginBottom: "16px" }}
      >
        返回首页
      </Button>

      <Card title="useRequest 自动刷新功能" style={{ marginBottom: "16px" }}>
        <Paragraph>
          <Text strong>功能说明：</Text> 测试 useRequest 的自动刷新功能， 从路由
          query 获取 id，当 id 变化时自动重新请求数据。
        </Paragraph>

        <Space direction="vertical" style={{ width: "100%" }}>
          <div>
            <Text strong>状态：</Text>
            {loading && <Tag color="processing">加载中...</Tag>}
            {error && <Tag color="error">错误: {error.message}</Tag>}
            {data && <Tag color="success">成功</Tag>}
            <Tag color="blue">当前ID: {currentId}</Tag>
          </div>
          <div>
            <Text strong>切换数据ID：</Text>
            <Space style={{ marginTop: "8px" }}>
              <Button
                type={currentId === 1 ? "primary" : "default"}
                onClick={() => handleIdChange(1)}
                loading={loading && currentId === 1}
              >
                数据1
              </Button>
              <Button
                type={currentId === 2 ? "primary" : "default"}
                onClick={() => handleIdChange(2)}
                loading={loading && currentId === 2}
              >
                数据2
              </Button>
              <Button
                type={currentId === 3 ? "primary" : "default"}
                onClick={() => handleIdChange(3)}
                loading={loading && currentId === 3}
              >
                数据3
              </Button>
              <Button
                type={currentId === 4 ? "primary" : "default"}
                onClick={() => handleIdChange(4)}
                loading={loading && currentId === 4}
              >
                数据4
              </Button>
              <Button
                type={currentId === 5 ? "primary" : "default"}
                onClick={() => handleIdChange(5)}
                loading={loading && currentId === 5}
              >
                数据5
              </Button>
            </Space>
          </div>
          <div>
            <Button onClick={handleRefresh} disabled={!data}>
              强制刷新当前数据
            </Button>
          </div>
          <Alert
            message="功能说明"
            description={
              <ul>
                <li>
                  <strong>自动刷新</strong>: 点击不同按钮切换 ID 时，useRequest
                  会自动重新请求数据
                </li>
                <li>
                  <strong>路由同步</strong>: ID 变化会同步到 URL 的 query 参数中
                </li>
                <li>
                  <strong>缓存机制</strong>: 相同 ID
                  的数据会被缓存，避免重复请求
                </li>
                <li>
                  <strong>强制刷新</strong>: 可以强制刷新当前数据，忽略缓存
                </li>
              </ul>
            }
            type="info"
            showIcon
          />
          {data && (
            <div>
              <Text strong>数据内容：</Text>
              <div style={{ marginTop: "8px" }}>
                <p>ID: {data.id}</p>
                <p>内容: {data.content}</p>
                <p>时间戳: {data.timestamp}</p>
                <p>版本: {data.version}</p>
              </div>
            </div>
          )}
        </Space>
      </Card>
    </div>
  );
};

export default RefreshPage;
